/*******************************************************************************
 * 工具方法
 * 
 * @param $
 */
(function($) {
	var $Util = {};
	var $jq = {};
	/**
	 * 正则表达式
	 */
	/** 元布尔表达式 */
	$Util.eleBooleanExprMin = /(true|false)((&&|\|\|)(true|false))*/;
	$Util.eleBooleanExprMin_g = /(true|false)((&&|\|\|)(true|false))*/g;
	/** 元布尔表达式,带括号 */
	$Util.eleBooleanExpr = /\((true|false)((&&|\|\|)(true|false))*\)/;
	/** 操作符 */
	$Util.opers = {
		'==' : {
			runFunc : function(a, b) {
				return $Util.compareEq(a, b);
			}
		},
		'!=' : {
			runFunc : function(a, b) {
				return $Util.compareNe(a, b);
			}
		},
		'>=' : {
			runFunc : function(a, b) {
				return $Util.compareGe(a, b);
			}
		},
		'<=' : {
			runFunc : function(a, b) {
				return $Util.compareLe(a, b);
			}
		},
		'>' : {
			runFunc : function(a, b) {
				return $Util.compareGt(a, b);
			}
		},
		'<' : {
			runFunc : function(a, b) {
				return $Util.compareLt(a, b);
			}
		}
	};
	/** 定制下拉框样式 */
	$Util.selModules = {
		'zteMulti' : {
			runFunc : function(id, option) {
				return $Util.initZteMultiSel(id, option);
			}
		}
	};
	/**
	 * 设置光标事件
	 */
	$Util.setSelectionRange = function(input, selectionStart, selectionEnd) {
		if (input.setSelectionRange) {
			input.focus();
			input.setSelectionRange(selectionStart, selectionEnd);
		} else if (input.createTextRange) {
			var range = input.createTextRange();
			range.collapse(true);
			range.moveEnd('character', selectionEnd);
			range.moveStart('character', selectionStart);
			range.select();
		}
	};
	$Util.setCaretToPos = function(input, pos) {
		this.setSelectionRange(input, pos, pos);
	};
	/**
	 * 计算布尔表达式
	 */
	/** （针对（true）&&false形式，不支持非运算） */
	$Util.calBoolean = function(input) {
		// console.log('input:'+input);
		match = this.eleBooleanExpr.exec(input);
		var self = this;
		while (match) {
			// console.log('match:'+match[0]);
			input = input.replace(self.eleBooleanExpr, self
					.calEleBoolean(match[0]));
			// console.log('replace:'+input);
			match = self.eleBooleanExpr.exec(input);
		}
		if (input.length >= 6) {
			input = self.calEleBoolean(input);
		}
		return input;
	};
	/** 计算元布尔表达式 */
	$Util.calEleBoolean = function(input) {
		if (!input) {
			return input;
		}
		// var srcScript = input;
		if (input.charAt(0) == '(') {
			input = input.substring(1, input.length - 1);
		}
		var errorStrMin = input.replace(this.eleBooleanExprMin_g, '');
		if (errorStrMin) {
			// console.log('error script:'+srcScript);
			// console.log('errorStrMin replace:'+errorStrMin);
			return 'error';
		}
		var bArr = input.split('&&');
		for (var i = 0; i < bArr.length; i++) {
			if (bArr[i] == 'false' || bArr[i].indexOf('true') < 0) {
				return 'false';
			}
		}
		return 'true';
	};
	/** 比较返回boolean */
	$Util.compare = function(a, oper, b) {
//		var self = this;
		var operObj = this.opers[oper];
		if (operObj) {
			return this.opers[oper].runFunc(a, b);
		}
		console.log('error:No such operation [' + oper + ']');
		return null;
	};
	$Util.compareEq = function(a, b) {
		return (a == b);
	};
	$Util.compareGt = function(a, b) {
		return (a > b);
	};
	$Util.compareGe = function(a, b) {
		return (a >= b);
	};
	$Util.compareLt = function(a, b) {
		return (a < b);
	};
	$Util.compareLe = function(a, b) {
		return (a <= b);
	};
	$Util.compareNe = function(a, b) {
		return (a != b);
	};
	/** 定制化下拉框初始化 */
	$Util.initCustomSel = function(type, id, option) {
		var initObj = this.selModules[type];
		if (initObj) {
			return initObj.runFunc(id, option);
		}
		console.log('error:No such select custom type [' + type + ']');
		return null;
	};
	$Util.initZteMultiSel = function(id, option) {
		option = option || {};
		var initOption = $.extend(true, {
			multiple : false,
			header : false
		}, option);
		var widget = new ZTEsoftMultiSelect(id).init(initOption);
		// 给选项增加title属性
		var $txtSpan =  $('.ui-multiselect-checkboxes span');
		$txtSpan.each(function(){
			$(this).attr('title',$(this).text());
		});
		var drpId = id;
		// 通过select_init的所有操作都被认为是select原生的操作
		window[drpId] = document.getElementById(drpId);
		window[drpId + "__widget__"] = widget;
		// 添加对下拉框的验证 add by he.shiwei35 2015-04-03
		var showBtn = window[drpId].nextSibling;
		var selClass = window[drpId].className;
		var setValFunc = function(value) {
			var setArr = initOption.multiple ? value : [ value ];
			if ($.isArray(setArr)) {
				widget.setValues(setArr);
			}
		};
		var getValFunc = function() {
			var valArr = widget.getValues();
			var retVal = initOption.multiple ? valArr : valArr[0];
			return retVal;
		};
		if (selClass) {
			var selClassArr = selClass.split(' ');
			for (var i = 0; i < selClassArr.length; i++) {
				if (selClassArr[i].indexOf('validate[') >= 0
						|| selClassArr[i].indexOf('__Multi') >= 0) {
					if (showBtn.className.indexOf(selClassArr[i]) < 0) {
						showBtn.className = showBtn.className + ' '
								+ selClassArr[i];
					}
				}
			}
		}
		// https://github.com/RubyLouvre/avalon/issues/272
		if ($.browser.msie) {
			Object.defineProperty(window[drpId], "value", {
				set : setValFunc,
				get : getValFunc
			});
			Object.defineProperty(showBtn, "value", {
				set : setValFunc,
				get : getValFunc
			});

			Object.defineProperty(window[drpId], "disabled", {
				set : function(flag) {
					$(this).multiselect("ie8Disabled", flag);
				},
				get : function() {
					return this.getAttribute("disabled") === "disabled" ? true
							: false;
				}
			});
		} else {
			window[drpId].__defineSetter__("value", setValFunc);
			window[drpId].__defineGetter__("value", getValFunc);
			showBtn.__defineSetter__("value", setValFunc);
			showBtn.__defineGetter__("value", getValFunc);

			window[drpId].__defineSetter__("disabled", function(flag) {
				$(this).multiselect("ie8Disabled", flag);
			});
			window[drpId].__defineGetter__("disabled", function() {
				return this.getAttribute("disabled") === "disabled" ? true
						: false;
			});
		}
		return widget;
	};
	$Util.START_ID = 100;
	$Util.getRowId = function() {
		return this.START_ID++;
	};
	$Util.isNull = function(str) {
		if (!str) {
			return true;
		}
		var strLow = str.toLowerCase();
		var nullMap = {
			'null' : true,
			'undefined' : true
		};
		return !!nullMap[strLow];
	};
	/***************************************************************************
	 * 封装方法
	 **************************************************************************/
	$.fn.focusEnd = function() {
		$Util.setCaretToPos(this[0], this.val().length);
	};
	/**
	 * 初始化下拉框 data：{val:{showName:valName}} define:showName is valName or
	 * resource key , default false（默认false,showName为资源文件KEY值） plzSel:need
	 * 'please select' or not , default false option:{__isCustom:true},extends
	 * parameters
	 */
	$.fn.initSelect = function(data, define, plzSel, option) {
		if ($(this).length === 0) {
			return null;
		}
		var sel = '';
		var tarId = $(this).attr('id');
		if (!tarId) {
			tarId = $.getRowId('sel_');
			$(this).attr('id', tarId);
		}
		if (plzSel === true) {
			sel = sel + '<option value="">' + PLZ_SELECT + '</option>';
		}
		if (data) {
			$.each(data, function(key, obj) {
				var showName = define === true ? obj.showName : Nebula.ResMgr
						.getString(obj.showName);
				var selected = obj.selected === true ? 'selected="selected"' : '';
				sel = sel + '<option value="' + key + '" ' + selected + '>'
						+ showName + '</option>';
			});
		}
		this.empty();
		this.append(sel);
		if (!option) {
			$.each(arguments, function(i, item) {
				if (i > 0 && $.isPlainObject(item)) {
					option = item;
					return false;
				}
			});
			if (!option) {
				option = {};
			}
		}
		var defaultOpt = {
			__isCustom : true,
			__type : 'zteMulti'
		};
		var opt = $.extend(defaultOpt, option);
		if (opt.__isCustom) {
			// 定制初始化下拉框样式
			return $Util.initCustomSel(opt.__type, tarId, opt);
		}
	};
	/**
	 * 搜索框添加暗影提示
	 */
	$.fn.searchTip = function(tip) {
		var cn = 'txt-searchTip';
		$(this).focus(function() {
			if ($(this).hasClass(cn)) {
				$(this).val('');
				$(this).removeClass(cn);
			}
		}).blur(function() {
			if (!this.value) {
				$(this).val(tip);
				$(this).addClass(cn);
			}
		});
		$(this).val(tip);
		$(this).addClass(cn);
	};
	/**
	 * 获取对象绑定的触发方法（非原装）
	 * type：触发方式（'keypress'...）
	 * charCode:按键charCode(13...)
	 */
	$.fn.getTriggerFunc = function(type,charCode,e){
		if($._data($(this)[0],'events')[type]){
			var $self = $(this);
			return function(){
				if(!e){
					e ={};
				}
				e.charCode = charCode|| e.charCode;
				$._data($self[0],'events')[type][0].handler.call($self,e);
			};
		}
		else{
			return null;
		}
	};
	$.fn.enterFunc = function(){
		var f =$(this).getTriggerFunc('keypress',13);
		if(f){
			f();
		}
	};
	/** ***************************************************** */

	$jq.calBooleanExpr = function(input) {
		if (!input) {
			return null;
		}
		return $Util.calBoolean(input);
	};
	$jq.compareValue = function(a, oper, b) {
		return $Util.compare(a, oper, b);
	};
	/** 设置资源文件显示值 */
	$jq.showResource = function(define) {
		$('.valKey').each(function() {
			var nameKey = $(this).attr('nameKey');
			var showName = define ? nameKey : Nebula.ResMgr.getString(nameKey);
			$(this).val(showName);
		});
		$('.txtKey').each(
				function() {
					if ($(this).find('span[name=reSpan]').length === 0) {
						var nameKey = $(this).attr('nameKey');
						var showName = define ? nameKey : Nebula.ResMgr
								.getString(nameKey);
						var span = '<span name="reSpan" >' + showName
								+ '</span>';
						$(this).prepend(span);
					}
				});
	};
	$jq.cleanObj = function(obj) {
		$.each(obj, function(key, value) {
			delete obj[key];
		});
	};
	/** 获取表格行主键 */
	$jq.getRowId = function(spChar) {
		spChar = spChar || 'row_';
		return spChar + $Util.getRowId();
	};
	$jq.isLogicNull = function(str) {
		return $Util.isNull(str);
	};
	/**
	 * 页面状态改变绑定方法
	 * obj:
	 * ex. pageState:{
	 * 				read:{keyName:'read',spName:'Read',canEdit:false,
				page:function(){readPage();}
				},
				edit:{keyName:'edit',spName:'Edit',canEdit:true,
					page:function(){editPage();}
				},
				add:{keyName:'add',spName:'Add',canEdit:true,
					page:function(){addPage();}
				}
	 * }
	 * spName 必填
	 */
	$jq.bindPageStateChg = function(obj,spStr){
		if(!obj){
			return null;
		}
		return function(state){
			if(obj[state]){
				spStr = spStr||'';
				var cssName = obj[state].spName;
				$('[class*=jq'+spStr+'Disabled]').prop('disabled',false);
				$('[class*=jq'+spStr+'Hide]').show();
				$('[class*=jq'+spStr+'Hidden]').css('visibility','visible');

				$('.jq'+spStr+'Disabled'+cssName).prop('disabled',true);
				$('.jq'+spStr+'Hide'+cssName).hide();
				$('.jq'+spStr+'Hidden'+cssName).css('visibility','hidden');
				//回调方法
				if($.isFunction(obj[state].page)){
					obj[state].page.call();
				}
			}
		};
	};

	$.extend($jq);
})(jQuery);
